package ldkxingzhe.ldkxingzhedemo.loader;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import ldkxingzhe.ldkxingzhedemo.R;
import ldkxingzhe.ldkxingzhedemo.utils.LogDemo;

/**
 * Created by liangdengke on 2015/9/9.
 */
public class ContactPhoneActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{

    private final String TAG = ContactPhoneActivity.class.getSimpleName();
    private SimpleCursorAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_loader);
        mAdapter = new SimpleCursorAdapter(this,
                R.layout.listview_simple_contat,
                null,
                new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1},
                new int[]{R.id.name,R.id.phone});
        ((ListView)findViewById(android.R.id.list)).setAdapter(mAdapter);
        getLoaderManager().initLoader(0,null,this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri mUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1
        };


        return new CursorLoader(this,mUri,projection,null,null,null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        LogDemo.v(TAG,"onLoadFinished");
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        LogDemo.v(TAG,"onLoaderReset");
        mAdapter.swapCursor(null);
    }
}
